import mysql from 'mysql'
import {mysqlconfig_qb} from '../config'
import variables from './variables'

var mysqlconnect = {

    getPool(mysqlConfig) {
        return mysql.createPool(mysqlConfig)
    },
    colsePool(poolname) {
       // console.log(poolname)
        poolname.end();
    },
    poolsInit() {
        for (let key in mysqlconfig_qb) {
            if (!variables.has(key)) {
                let pool = this.getPool(config[key])
                variables.set(key, pool)

            }
        }
    },
    poolsEnd() {
        for (let key in mysqlconfig_qb) {
            this.colsePool(variables.get(key))
            variables.delete(key)
        }
    },
    queryWithCb (pool,sql,sqlparam,callback) {
        pool.getConnection(function (err,conn) {
            if (err){
                callback(null,err,null)
            } else {
                conn.query(sql,sqlparam,function (qerr,vals,fields) {
                    conn.release();
                    callback(qerr,vals,fields)
                })
            }
        })
    },

    query(pool,sql,sqlparam){
        return new Promise(
            (resolve, reject) => {
                this.queryWithCb(pool,sql,sqlparam,function (qerr,vals,field) {
                    resolve(vals)
                })
            }
        )
    }


}
module.exports = mysqlconnect
